<script setup lang="ts">
//引入
import CustomNavbar from './components/CustomNavbar.vue';
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from "vue"
import { useGuessList } from '@/composables'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
  console.log('轮播图数据', res);
}

// 获取分类组件数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
  console.log('分类组件数据', res);
}

// 获取分类组件数据
const hotPanelList = ref<HotItem[]>([])
const getHomeHotPanelData = async () => {
  const res = await getHomeHotAPI()
  hotPanelList.value = res.result
  console.log('热门推荐组件数据', res);
}
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  // getHomeBannerData()
  // getHomeCategoryData()
  // getHomeHotPanelData()
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotPanelData()])
  isLoading.value = false
})
// 获取猜你喜欢组件实例
const {guessRef,onScrolltolower} = useGuessList()
// const guessRef = ref<XtxGuessInstance>()
// // 滚动触底
// const onScrolltolower = () => {
//   console.log('滚动触底了', guessRef);
//   guessRef.value?.getMore()
// }

// 当前下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新事件
const onRefresherrefresh = async () => {
  console.log('自定义下拉刷新事件')
  // 开始动画
  isTriggered.value = true
  // 加载数据
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotPanelData()
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData()
  // 优化加载数据,多个promise请求外套一个promise，里面是同步请求
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotPanelData(), guessRef.value?.getMore()])
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 顶部面板组件 -->
  <CustomNavbar />
  <!-- 滚动容器 refresher-enabled开启下拉刷新,refresherrefresh下拉监听事件,scrolltolower滚动监听事件-->
  <scroll-view refresher-enabled @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered"
    @scrolltolower="onScrolltolower" class="scroll-view" scroll-y>
    <PageSkeleton v-if="isLoading" />
    <!-- 轮播图自定义公共组件 -->
    <XtxSwiper :list="bannerList" />
    <!-- 分类面板组件 -->
    <CategoryPanel :list="categoryList" />
    <!-- 热门推荐组件 -->
    <HotPanel :list="hotPanelList" />
    <!-- 猜你喜欢组件 -->
    <XtxGuess ref="guessRef" />
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
